<template>
    <div class="app-container">
      {{student}}
      <el-card shadow="always">
        <el-form ref="form" :model="student" label-width="100px">
          <el-form-item label="学生姓名">
            <el-input v-model="student.sname"></el-input>
          </el-form-item>
          <el-form-item label="学生性别">
            <el-radio v-model="student.sex" label="男">男</el-radio>
            <el-radio v-model="student.sex" label="女">女</el-radio>
          </el-form-item>
          <el-form-item label="学生年龄">
            <el-input v-model="student.age"></el-input>
          </el-form-item>
          <el-form-item label="添加住址">
            <el-input v-model="student.addr"></el-input>
          </el-form-item>

          <el-form-item label="所在班级">
            <el-select v-model="student.cid" placeholder="请选择所在班级">
              <el-option :label="c.cname" :value="c.cid" v-for="c in classes" :key="c.cid"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="save">保存学生</el-button>
            <el-button>取消</el-button>
          </el-form-item>
        </el-form>
      </el-card>

    </div>
</template>

<script>
  import classesApi from "@/api/classes"
  import studentApi from '@/api/students'
    export default {
        data(){
          return {
            classes:[],
            student:{},
            id: ''
          }
        },
      created() {
          this.findClasses()
          this.findById()
      },
      methods:{
          // 根据id查询学生
          findById(){
            // 得到传入的学生id参数
            this.id = this.$route.params.id
            console.log("id:",this.id)
            if(this.id){
              studentApi.findById(this.id).then(({data}) => {
                console.log(data)
                this.student = data.student
              })
            }

          },
          //0. 查询所有班级
          findClasses(){
            classesApi.findClasses().then(({data}) => {
              this.classes = data.list
            })
          },
          //1. 保存学生
          save(){
            //添加或修改的url地址
            let url = "/student/add"
            if(this.student.sid){
              url = "/student/update"
            }
            studentApi.save(url,this.student).then((data) => {
              if(data.code === 0){
                this.$message.success(data.message)
                this.$router.push("/student/list")
              }
            })
          }
        }
    }
</script>

<style scoped>
  .el-card{
    width: 600px;
  }
</style>
